package com.med.interceptor;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * Project:internet-based-healthcare
 * Package:com.med.interceptor
 *
 * @Description:
 * @Author:其一
 * @CreateTime: 2025-08-25-11-55
 */
@Component
public class AuthInterceptor implements HandshakeInterceptor {
    @Autowired
    private TokenService tokenService;
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String token = request.getHeaders().getFirst(SecurityConstants.AUTHORIZATION_HEADER);
        if (!StringUtils.hasText(token)) {
            return false;
        }
        LoginUser loginUser = tokenService.getLoginUser(token);
        if (loginUser == null) {
            return false;
        }

        attributes.put("userId", loginUser.getUserid());
        attributes.put("username", loginUser.getUsername());


        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
